import React, { useState, useEffect } from 'react';
import { useForm } from 'antd/lib/form/Form';
import { Drawer, Button, Input, Form, Radio, Space, Divider, message } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Store } from 'antd/lib/form/interface';
import { addWebInterface, modifyWebInterface, getWebInterface } from '../../servers/servers';

type Props = {
  /**
   * 显示/隐藏抽屉弹框
   */
  show: boolean;
  /**
   * 关闭事件
   */
  onClose: () => void;
  /**
   * 成功回调
   */
  onSuccess: () => void;
  /**
   * 版本id
   */
  versionId: number;
  /**
   * 接口Id: 传Id-编辑, 不传Id或0-创建
   */
  interfaceId?: number;
};

/**
 * 创建/编辑接口组件
 * 示例：AI管理-机器人管理-版本管理-配置话术流程-基础资源-接口管理-新增接口
 */
export const OperateInterface: React.FC<Props> = props => {
  const [form] = useForm();
  // 确定按钮loading
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  /**
   * 关闭弹框
   */
  const closeDrawer = () => {
    form.resetFields();
    props.onClose();
  };

  /**
   * 确认
   */
  const onFinish = async (values: Store) => {
    console.log('onFinish -> values', values);
    setConfirmLoading(true);
    const {
      interfaceName,
      callMode,
      url,
      requestParams: requestParamsOrigin,
      responseParams: responseParamsOrigin,
    } = values;
    const requestParams = requestParamsOrigin.filter(
      (item: { interfaceParam: string }) => item.interfaceParam
    );
    const responseParams = responseParamsOrigin.filter(
      (item: { interfaceParam: string }) => item.interfaceParam
    );
    try {
      if (props.interfaceId) {
        // 编辑
        const res = await modifyWebInterface({
          interfaceName: interfaceName.trim(),
          callMode,
          url,
          requestParams,
          responseParams,
          versionId: props.versionId,
          interfaceId: props.interfaceId,
        });
        if (res.code === 0) {
          message.success(`更新成功`);
          props.onSuccess();
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      } else {
        // 新建
        const res = await addWebInterface({
          interfaceName: interfaceName.trim(),
          callMode,
          url,
          requestParams,
          responseParams,
          versionId: props.versionId,
        });
        if (res.code === 0) {
          message.success(`创建成功`);
          props.onSuccess();
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setConfirmLoading(false);
  };

  useEffect(() => {
    const initForm = async () => {
      let initForm = {
        interfaceName: '',
        callMode: 'get',
        url: '',
        requestParams: [{}],
        responseParams: [{}],
      };
      if (props.interfaceId && props.show) {
        // 编辑
        try {
          const res = await getWebInterface({
            interfaceId: props.interfaceId,
          });
          if (res.code === 0) {
            const {
              interfaceName = '',
              callMode = 'get',
              url = '',
              requestParams,
              responseParams,
            } = res.data;

            initForm = {
              interfaceName,
              callMode,
              url,
              requestParams: requestParams || [{}], // 防止数据是null
              responseParams: responseParams || [{}], // 防止数据是null
            };
            console.log('initForm -> initForm', initForm);
          } else {
            message.error(`${res.tips}(错误码: ${res.code})`);
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      }
      form.setFieldsValue(initForm);
    };
    initForm();
  }, [form, props.interfaceId, props.show]);

  return (
    <>
      <Drawer
        title={`${props.interfaceId ? '编辑接口' : '新增接口'}`}
        placement="right"
        getContainer={false}
        width={520}
        closable={false}
        onClose={closeDrawer}
        visible={props.show}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={closeDrawer} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={() => form.submit()} type="primary" loading={confirmLoading}>
              确定
            </Button>
          </div>
        }
      >
        <Form
          layout="horizontal"
          labelCol={{ span: 4, offset: 0 }}
          form={form}
          onFinish={onFinish}
          initialValues={{
            interfaceName: '',
            callMode: 'get',
            url: '',
            requestParams: [{}],
            responseParams: [{}],
          }}
        >
          <Form.Item
            name="interfaceName"
            label="接口名称"
            rules={[{ required: true, whitespace: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="callMode" label="请求方式" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value="get">get</Radio>
              <Radio value="post">post</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="url" label="接口地址" rules={[{ required: true, whitespace: true }]}>
            <Input />
          </Form.Item>
          <Divider />
          <Form.List name="requestParams">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map(field => (
                    <Space
                      key={field.key}
                      style={{ display: 'flex', marginBottom: 8 }}
                      align="baseline"
                    >
                      <Form.Item
                        {...field}
                        name={[field.name, 'interfaceParam']}
                        fieldKey={[field.fieldKey, 'interfaceParam']}
                        // rules={[{ required: true, whitespace: true }]}
                        labelCol={{ span: 9 }}
                        label="请求参数"
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        name={[field.name, 'internalParam']}
                        fieldKey={[field.fieldKey, 'internalParam']}
                        labelCol={{ span: 9 }}
                        label="内部参数"
                      >
                        <Input />
                      </Form.Item>

                      {fields.length > 1 && (
                        <MinusCircleOutlined
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      )}
                    </Space>
                  ))}

                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add();
                      }}
                      block
                    >
                      <PlusOutlined /> 添加参数
                    </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.List>
          <Divider />
          <Form.List name="responseParams">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map(field => (
                    <Space
                      key={field.key}
                      style={{ display: 'flex', marginBottom: 8 }}
                      align="baseline"
                    >
                      <Form.Item
                        {...field}
                        name={[field.name, 'interfaceParam']}
                        fieldKey={[field.fieldKey, 'interfaceParam']}
                        // rules={[{ required: true, whitespace: true }]}
                        labelCol={{ span: 9 }}
                        label="返回参数"
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        name={[field.name, 'internalParam']}
                        fieldKey={[field.fieldKey, 'internalParam']}
                        labelCol={{ span: 9 }}
                        label="内部参数"
                      >
                        <Input />
                      </Form.Item>

                      {fields.length > 1 && (
                        <MinusCircleOutlined
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      )}
                    </Space>
                  ))}

                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add();
                      }}
                      block
                    >
                      <PlusOutlined /> 添加参数
                    </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.List>
        </Form>
      </Drawer>
    </>
  );
};
